package memory;

import java.nio.ByteBuffer;

public class MemoryTest {

    /**
     * 分配堆内存
     */
    public static void allocateJVM(){
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            ByteBuffer.allocate(100);
        }
        long end = System.currentTimeMillis();
        System.out.println("JVM堆内存分配耗时：" + (end - start));
    }

    /**
     * 分配直接内存
     */
    public static void allocateDirect(){
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            ByteBuffer.allocateDirect(100);
        }
        long end = System.currentTimeMillis();
        System.out.println("直接内存分配耗时：" + (end - start));
    }

    /**
     * 读写JVM内存
     */
    public static void readWriteJVM(){
        long start = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for(int j = 0;j < 200;j++){
                buffer.getInt();
            }
            buffer.clear();
        }
        long end = System.currentTimeMillis();
        System.out.println("JVM内存读写时间：" + (end - start));
    }

    /**
     * 读写直接内存
     */
    public static void readWriteDirect(){
        long start = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for(int j = 0;j < 200;j++){
                buffer.getInt();
            }
            buffer.clear();
        }
        long end = System.currentTimeMillis();
        System.out.println("直接内存读写时间：" + (end - start));
    }

    public static void main(String[] args) {
        //JVM分配JVM内存效率高于直接内存
//        allocateJVM();
//        allocateDirect();
        for (int i = 0; i < 10; i++) {
            readWriteJVM();
            readWriteDirect();
        }
    }
}
